/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedLineData, pickedVertexData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useState } from 'react';

enum Continuity {
  Position = 0,
  Tangent = 1,
  Curvature = 3,
}

enum KeepOtherEnd {
  None = -1,
  Position = 0,
  Tangent = 1,
  Curvature = 2,
}

type FormData = {
  curve1: {
    id?: pickedLineData;
    point?: pickedVertexData;
    continuity: Continuity;
  };
  curve2: {
    id?: pickedLineData;
    point?: pickedVertexData;
    keepOtherEnd: KeepOtherEnd;
  };
};

type Params = {
  mode: 'Normal';
  curve1: {
    id: string;
    point: string;
    continuity: Continuity;
    keepOtherEnd: KeepOtherEnd;
  };
  curve2: { id: string; point: string };
};

function CommandMatchCurve({ title, onClose, props }: CurvedCmdDialogParams) {
  const initData: FormData = {
    curve1: {
      continuity: Continuity.Position,
    },
    curve2: {
      keepOtherEnd: KeepOtherEnd.Position,
    },
  };

  const [formData, setFormData] = useState<FormData>(initData);

  const { picker } = useTools();

  const execute = async (preview: boolean) => {
    const { curve1, curve2 } = formData;

    const params: Params = {
      mode: 'Normal',
      curve1: {
        id: curve1.id.edgeId,
        point: curve1.point.vertexId,
        continuity: curve1.continuity,
        keepOtherEnd: curve2.keepOtherEnd,
      },
      curve2: {
        id: curve2.id.edgeId,
        point: curve2.point.vertexId,
      },
    };

    await confirmCommand({ type: 'Match', a: params }, preview);
  };

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const { curve1, curve2 } = params;

    await initEditDependency([
      curve1.id,
      curve1.point,
      curve2.id,
      curve2.point,
    ]);

    setFormData({
      curve1: {
        id: picker.generatePickObjByPickID(curve1.id) as pickedLineData,
        point: picker.generatePickObjByPickID(curve1.point) as pickedVertexData,
        continuity: curve1.continuity,
      },
      curve2: {
        id: picker.generatePickObjByPickID(curve2.id) as pickedLineData,
        point: picker.generatePickObjByPickID(curve2.point) as pickedVertexData,
        keepOtherEnd: curve1.keepOtherEnd,
      },
    });
  }, []);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    execute(false);

    onClose();
  };

  const {
    initEditDependency,
    initingEdit,
    confirmCommand,
    clear,
    isLoading,
    isPreviewLoading,
  } = useCommand('cmd-match-curve', {
    commandName: 'CreateCurve',
    editDxid: props?.shape,
    onClose,
    finishDraw: checkAndFinishDraw,
  });

  const isFormDataValid = () => {
    const { curve1, curve2 } = formData;

    return (
      curve1.id != null &&
      curve1.point != null &&
      curve2.id != null &&
      curve2.point != null
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      curve1: {
        type: 'object',
        title: '',
        properties: {
          id: {
            type: 'string',
            format: PickInputRJSFFormat.PickCurve,
          },
          point: {
            type: 'string',
            format: PickInputRJSFFormat.PickVertex,
          },
          continuity: {
            title: '连续方式',
            type: 'number',
            oneOf: [
              {
                type: 'number',
                title: '位置',
                const: 0,
              },
              {
                type: 'number',
                title: '切线',
                const: 1,
              },
              {
                type: 'number',
                title: '曲率',
                const: 3,
              },
            ],
            default: 0,
          },
        },
      },
      curve2: {
        type: 'object',
        title: '',
        properties: {
          id: {
            type: 'string',
            format: PickInputRJSFFormat.PickCurve,
          },
          point: {
            type: 'string',
            format: PickInputRJSFFormat.PickVertex,
          },
          keepOtherEnd: {
            title: '连续方式',
            type: 'number',
            oneOf: [
              {
                type: 'number',
                title: '不保持',
                const: -1,
              },
              {
                type: 'number',
                title: '位置',
                const: 0,
              },
              {
                type: 'number',
                title: '切线',
                const: 1,
              },
              {
                type: 'number',
                title: '曲率',
                const: 2,
              },
            ],
            default: 0,
          },
        },
      },
    },
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      submitLoading={isLoading}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        curve1: {
          id: {
            'ui:autofocus': true,
            'ui:placeholder': '请输入曲线1',
          },
          point: {
            'ui:placeholder': '请输入曲线1上的点',
          },
        },
        curve2: {
          id: {
            'ui:placeholder': '请输入曲线2',
          },
          point: {
            'ui:placeholder': '请输入曲线2上的点',
          },
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdMatchCurve: CurvedBaseCommand = {
  id: 'CmdMatchCurve',
  label: 'command.match-curve',
  icon: 'commands/curved/match-curve',
  create: (label, onClose, props) => (
    <CommandMatchCurve
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
